package com.kyzh.core.pager.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.gushenge.atools.util.setWidth
import com.gushenge.core.beans.*
import com.gushenge.core.requests.HomeRequest
import com.kyzh.core.R
import com.kyzh.core.activities.*
import com.kyzh.core.adapters.*
import com.kyzh.core.adapters.v3.GameListBorderAdapter
import com.kyzh.core.databinding.IncludeTuiBinding
import com.kyzh.core.databinding.ItemHomeImgBinding
import com.kyzh.core.databinding.ItemHomeRecomGongnengBinding
import com.kyzh.core.databinding.ItemHomeRecomTui3Binding
import com.gushenge.core.base.fragment.BaseFragment
import com.kyzh.core.pager.gamedetail.GameDetailActivity1
import com.kyzh.core.pager.weal.gift.GiftActivity
import com.kyzh.core.pager.weal.rank.RankActivity
import com.kyzh.core.pager.weal.serverlist.ServerActivity
import com.kyzh.core.uis.RecyclerViewAtViewPager2
import com.kyzh.core.utils.*
import com.kyzh.core.utils.ViewUtils.dp
import com.makeramen.roundedimageview.RoundedImageView
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.zhpan.bannerview.BannerViewPager
import com.zhpan.bannerview.constants.PageStyle
import kotlinx.android.synthetic.main.fragment_homerecom.*
import net.center.blurview.ShapeBlurView
import net.center.blurview.enu.BlurMode
import org.jetbrains.anko.support.v4.dip
import org.jetbrains.anko.support.v4.startActivity

class HomeRecomFragment : BaseFragment() {

    private val beans = arrayListOf<HomeV3MultiItem>()
    private val adapter = Adapter(beans)
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_homerecom, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        srlRoot.setOnRefreshListener {
            GSYVideoManager.onPause()
            initData()
        }
        val linearLayoutManager = LinearLayoutManager(requireContext())
        rvRecom.layoutManager =linearLayoutManager
        rvRecom.adapter = adapter
        rvRecom.addOnScrollListener(object :RecyclerView.OnScrollListener(){
            var firstVisibleItem = 0
            var lastVisibleItem:Int = 0

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition()
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition()
                kotlin.runCatching {
                    if ( firstVisibleItem != 0) {
                        val viewByPosition = adapter.getViewByPosition(0, R.id.banner)
                        viewByPosition as BannerViewPager<Slide>
                        viewByPosition.stopLoop()
                    }else{
                        val viewByPosition = adapter.getViewByPosition(0, R.id.banner)
                        viewByPosition as BannerViewPager<Slide>
                        viewByPosition.startLoop()
                    }

                }
            }
        })
        rvRecom.setItemViewCacheSize(50)
        srlRoot.isRefreshing = true
//        initData()
    }

    override fun onPause() {
        super.onPause()

        GSYVideoManager.onPause()
    }

    override fun onResume() {
        super.onResume()
        initData()
    }

    private fun initData(){
        HomeRequest.recom1 {
            val sort = fenlei
            beans.clear()  // 一下位置改动代码位置即可更改排序
            if(!slide.isNullOrEmpty()){
                beans.add(HomeV3MultiItem(slide = slide,style = 0))  //顶部banner
            }
            if(!fanli_news.isNullOrEmpty()){
                beans.add(HomeV3MultiItem(fanli_news = fanli_news,style = 9))  //消息返利
            }
            if(!gongneng.isNullOrEmpty()){
                beans.add(HomeV3MultiItem(gongneng = gongneng,style = 8)) //功能区域
            }
            if(!tuijian.isNullOrEmpty()){
                beans.add(HomeV3MultiItem(tuijian = tuijian,style = 5))//重磅推荐
            }

            if(!main_slide.isNullOrEmpty()){
                beans.add(HomeV3MultiItem(main_slide = main_slide,style = 10))//重磅推荐
            }
            kotlin.runCatching {
                if(!game.isNullOrEmpty()){
                    beans.add(HomeV3MultiItem(fenlei1 = fenlei[0],tuijian = game[0],style = 7))  // 热门游戏
                    fenlei.removeAt(0)   //  游戏是中间插入的  所以用完就删了
                    game.removeAt(0)  //  游戏是中间插入的  所以用完就删了
                }
            }
            if(!guanfangtuijian.isNullOrEmpty()){
                beans.add(HomeV3MultiItem(guanfangtuijian = guanfangtuijian,style = 6)) // 官方推荐
            }
//            beans.add(HomeV3MultiItem(style = 1))
//            beans.add(HomeV3MultiItem(tuijian = tuijian,style = 2))
            // 将游戏列表都显示处理
            game.forEachIndexed { index, arrayList ->
                    beans.add(HomeV3MultiItem(tuijian = game[index],fenlei1 = sort[index],style =  7))
            }
            // 分类显示
            if(!fenlei.isNullOrEmpty()){
                beans.add(HomeV3MultiItem(fenlei = fenlei,style = 4))
            }
            adapter.notifyDataSetChanged()
        }

        srlRoot.isRefreshing = false
    }

    private inner class Adapter(beans:ArrayList<HomeV3MultiItem>):BaseMultiItemQuickAdapter<HomeV3MultiItem,BaseViewHolder>(beans){

        init {
            addItemType(0,R.layout.item_home_recom_banner)
            addItemType(1,R.layout.item_home_recom_function)
            addItemType(2,R.layout.item_home_recom_recom)
            addItemType(3,R.layout.item_home_recom_game)
            addItemType(4,R.layout.item_home_recom_tui)
            addItemType(5,R.layout.item_home_recom_tui)
            addItemType(6,R.layout.item_home_recom_tui)
            addItemType(7,R.layout.item_home_recom_tui)
            addItemType(8,R.layout.item_home_recom_tui_gongneng)
            addItemType(9,R.layout.item_autoscrollview)
            addItemType(10,R.layout.item_home_rev)
        }

        override fun convert(holder: BaseViewHolder, item: HomeV3MultiItem) {
            when(holder.itemViewType){
                0->{
                    val banner = holder.getView<BannerViewPager<Slide>>(R.id.banner)
                    banner.setLifecycleRegistry(lifecycle)
                            .setOnPageClickListener { a,b->
                                context.startGameDetailActivity(item.slide[b].gid)
                            }
                            .setAdapter(BannerAdapter(context))
                            .setInterval(5000)
                            .setPageMargin(dip(10))
                            .setRevealWidth(dip(10))
                            .setPageStyle(PageStyle.MULTI_PAGE_SCALE)
                            .create(item.slide)
                }
                1->{
                    holder.getView<ConstraintLayout>(R.id.ll1).setOnClickListener {
                        startActivity<ServerActivity>()
                    }
                    holder.getView<ConstraintLayout>(R.id.ll2).setOnClickListener {
                        if (startLogin()){
                            startActivity<GiftActivity>()
                        }
                    }
                    holder.getView<ConstraintLayout>(R.id.ll3).setOnClickListener {
                        startActivity<RankActivity>()
                    }
                }
                2->{
                    val icon: ImageView = holder.getView(R.id.ivGameIcon)
                    val name: TextView = holder.getView(R.id.tvGameName)
                    val type: TextView = holder.getView(R.id.tvGameType)
                    val tvDetail: TextView = holder.getView(R.id.tvDetail)
                    val bq: RecyclerView = holder.getView(R.id.bq)
                    icon.loadImage(item.tuijianOther.icon)
                    name.text = item.tuijianOther.name
                    type.text = "${item.tuijianOther.point}  ${item.tuijianOther.type}"
                    bq.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
                    bq.adapter = BqSoildAdapter(R.layout.bq_item, item.tuijianOther.biaoqian)
                    holder.itemView.setOnClickListener {
                        startGameDetailActivity(item.tuijianOther.gid)
                    }
                }
                3 -> {
                    val icon: ImageView = holder.getView(R.id.ivGameIcon)
                    val topBg: RoundedImageView = holder.getView(R.id.ivTopBg)
                    val cl1: ConstraintLayout = holder.getView(R.id.cl1)
                    val name: TextView = holder.getView(R.id.tvGameName)
                    val type: TextView = holder.getView(R.id.tvGameType)
                    val tvTitle: TextView = holder.getView(R.id.tv1)
                    val tvDetail: TextView = holder.getView(R.id.tvDetail)
                    val bq: RecyclerView = holder.getView(R.id.bq)
                    val rvList: RecyclerView = holder.getView(R.id.rvList)
                    icon.loadImage(item.tuijianOther.icon)
                    topBg.loadImage(item.tuijianOther.image)
                    name.text = item.tuijianOther.name
                    tvTitle.text = item.gameTop
                    type.text = "${item.tuijianOther.point}  ${item.tuijianOther.type}"
                    bq.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
                    bq.adapter = BqSoildAdapter(R.layout.bq_item, item.tuijianOther.biaoqian)
                    tvDetail.setOnClickListener {
                        startGameDetailActivity(item.tuijianOther.gid)
                    }
                    cl1.setOnClickListener {
                        startGameDetailActivity(item.tuijianOther.gid)
                    }
                    topBg.setOnClickListener {
                        startGameDetailActivity(item.tuijianOther.gid)
                    }
                    rvList.layoutManager = object : LinearLayoutManager(requireContext()) {
                        override fun canScrollHorizontally(): Boolean {
                            return false
                        }

                        override fun canScrollVertically(): Boolean {
                            return false
                        }
                    }
                    rvList.adapter = GameListBorderAdapter(R.layout.item_game_border, item.game1)
                }
                4->{
                    val view = holder.getView<ImageView>(R.id.v1)
                    view.setImageResource(R.drawable.icon_home_title3)
                    val tv1: TextView = holder.getView(R.id.tv1)
                    tv1.setText(getString(R.string.otherHotCategory))
                    val rvList: RecyclerView = holder.getView(R.id.rvList)
                    rvList.layoutManager = FlexboxLayoutManager(context,FlexDirection.ROW,FlexWrap.WRAP)
                    rvList.adapter = SortAdapter(R.layout.item_home_recom_sort_item,item.fenlei)

                }
                5 ->{
                    val tv1 = holder.getView<TextView>(R.id.tv1)
                    tv1.text = "重磅推荐"
                    val tag = holder.getView<TextView>(R.id.tag)
                    tag.text = "不能错过的精品游戏"
                    val view = holder.getView<ImageView>(R.id.v1)
                    view.setImageResource(R.drawable.icon_home_title1)
                    val rvList: RecyclerView = holder.getView(R.id.rvList)
                    val view1 = holder.getView<ConstraintLayout>(R.id.content)
//                    view1.setBackgroundResource(R.drawable.bg_zhongbang)

                    view1.backgroundTintList = null
                    rvList.layoutManager =object :GridLayoutManager(context,2){
                        override fun canScrollHorizontally(): Boolean {
                            return false
                        }

                        override fun canScrollVertically(): Boolean {
                            return false
                        }
                    }
                    rvList.adapter = TuijianAdapter(item.tuijian)
                }
                6 ->{
                    val tv1 = holder.getView<TextView>(R.id.tv1)
                    tv1.text = "官方推荐"
                    val view = holder.getView<ImageView>(R.id.v1)
                    view.setImageResource(R.drawable.icon_home_title2)
                    val rvList: RecyclerView = holder.getView(R.id.rvList)
                    rvList.layoutManager= object : LinearLayoutManager(requireContext()) {
                        override fun canScrollHorizontally(): Boolean {
                            return false
                        }

                        override fun canScrollVertically(): Boolean {
                            return false
                        }
                    }
                    rvList.adapter = GuanfangAdapter(item.guanfangtuijian)
                }
                7 ->{
                    val tv1 = holder.getView<TextView>(R.id.tv1)
                    tv1.text = item.fenlei1.name
                    val view = holder.getView<ImageView>(R.id.v1)
                    view.loadImage(item.fenlei1.icon)
                    val rvList: RecyclerView = holder.getView(R.id.rvList)
                    rvList.layoutManager = object : LinearLayoutManager(requireContext()) {
                        override fun canScrollHorizontally(): Boolean {
                            return false
                        }

                        override fun canScrollVertically(): Boolean {
                            return false
                        }
                    }
                    rvList.adapter = HomeChosenAdapter(item.tuijian,holder.position.toString())
                }
                8 ->{
                    val rvList: RecyclerView = holder.getView(R.id.rvList)
//                    val pagerGridLayoutManager =  PagerGridLayoutManager(2, 5, PagerGridLayoutManager.HORIZONTAL)
                    rvList.post {
//                        var list = arrayListOf<Int>()
//                        for (a in 1..pagerGridLayoutManager.pagerCount){
//                            list.add(0)
//                        }
//
//
//                        list[0] = 1
//                        val revLin = holder.getView<RecyclerView>(R.id.revLin)
//                        if(pagerGridLayoutManager.pagerCount<2){
//                            revLin.setVisibility(false)
//                        }else{
//                            revLin.setVisibility(true)
//                        }

//                        revLin.layoutManager = LinearLayoutManager(requireContext(),RecyclerView.HORIZONTAL,false)
//                        val revLinAdapter = object :BaseQuickAdapter<Int ,BaseViewHolder>(R.layout.item_home_line_img,list){
//                            override fun convert(holder: BaseViewHolder, item: Int) {
//                                val view = holder.getView<ImageView>(R.id.iv)
//                                if(item == 0){
//                                    view.setWidth(dip(10))
//                                    view.setImageResource(R.drawable.bg_line_noselect)
//                                }else{
//                                    view.setWidth(dip(22))
//                                    view.setImageResource(R.drawable.bg_line_select)
//                                }
//                            }
//
//                        }
//                        revLin.adapter = revLinAdapter
//                        pagerGridLayoutManager.setPagerChangedListener(object :PagerGridLayoutManager.PagerChangedListener{
//                            override fun onPagerCountChanged(pagerCount: Int) {
//                            }
//
//                            override fun onPagerIndexSelected(
//                                prePagerIndex: Int,
//                                currentPagerIndex: Int
//                            ) {
//                                list[prePagerIndex] =0
//                                list[currentPagerIndex] =1
//                                revLinAdapter.notifyDataSetChanged()
//                            }
//                        })
                    }
                    rvList.layoutManager = GridLayoutManager(context,5)
                    rvList.adapter = GongNengAdapter(item.gongneng)
                }
                9->{
                    val rvList: com.kyzh.core.uis.AutoScrollView = holder.getView(R.id.news_title)
                    rvList.adapter = HomeNewsAdapter(requireActivity(), item.fanli_news, 24.dp)
                }
                10->{
                    var list = mutableListOf<Int>()
                    val rvList: RecyclerViewAtViewPager2 = holder.getView(R.id.rev)
                    val revLin = holder.getView<RecyclerView>(R.id.revLin)
                    // 不能重复添加  所以
                    if( rvList.onFlingListener==null){
                        LinearSnapHelper().attachToRecyclerView(rvList)
                    }
                    rvList.layoutManager = LinearLayoutManager(requireContext(),RecyclerView.HORIZONTAL,false)
                    revLin.layoutManager = LinearLayoutManager(requireContext(),RecyclerView.HORIZONTAL,false)

                    rvList.adapter = KaiTongAdapter(item.main_slide)

                    if(item.main_slide!=null &&item.main_slide.size>1){
                        revLin.setVisibility(true)
                    }else{
                        revLin.setVisibility(false)
                    }
                    for (a in 1..item.main_slide.size){
                        list.add(0)
                    }
                    val revLinAdapter = object :BaseQuickAdapter<Int ,BaseViewHolder>(R.layout.item_home_line_img,list){
                        override fun convert(holder: BaseViewHolder, item: Int) {
                            val view = holder.getView<ImageView>(R.id.iv)
                            if(item == 0){
                                view.setWidth(dip(10))
                                view.setImageResource(R.drawable.bg_line_noselect)
                            }else{
                                view.setWidth(dip(22))
                                view.setImageResource(R.drawable.bg_line_select)
                            }
                        }

                    }
                    revLin.adapter = revLinAdapter

                    rvList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                            super.onScrolled(recyclerView, dx, dy)
                            val position: Int = (rvList.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
                            list.forEachIndexed { index, i ->
                                list[index] = 0
                            }
                            list[position] =1

                            revLinAdapter.notifyDataSetChanged()
                        }
                    })

                }
            }
        }
    }

    private inner class KaiTongAdapter(nav: ArrayList<Nav>):BaseQuickAdapter<Nav,BaseDataBindingHolder<ItemHomeImgBinding>>(R.layout.item_home_img,nav){
        override fun convert(holder: BaseDataBindingHolder<ItemHomeImgBinding>, item: Nav) {
            holder .dataBinding?.data = item
            item.login = 1
            holder.dataBinding?.rev?.setOnClickListener {
                context.navClickByLogin(item)
            }
        }
    }



    private inner class GongNengAdapter(beans:ArrayList<GongNeng>):BaseQuickAdapter<GongNeng,BaseDataBindingHolder<ItemHomeRecomGongnengBinding>>(R.layout.item_home_recom_gongneng,beans){
        override fun convert(
            holder: BaseDataBindingHolder<ItemHomeRecomGongnengBinding>,
            item: GongNeng
        ) {
            holder.setIsRecyclable(true)
            holder.dataBinding?.apply {
                data = item
            }
            holder.itemView.setOnClickListener {
                val nav = Nav().apply {
                    name = item.name
                    type = item.type
                    icon = item.icon
                    login = item.login
                    url = item.url
                }
                if(nav.type == 0 && nav.name == "更多福利"){
                    val mainActivity = context as MainActivity
                    mainActivity.fuli()
                }else{
                    context.navClickByLogin(nav)
                }
            }
        }

    }


    //官方推荐的adapter
    private inner class GuanfangAdapter(beans:ArrayList<Guanfangtuijian>):BaseQuickAdapter<Guanfangtuijian,BaseDataBindingHolder<ItemHomeRecomTui3Binding>>(R.layout.item_home_recom_tui3,beans){
        override fun convert(
            holder: BaseDataBindingHolder<ItemHomeRecomTui3Binding>,
            item: Guanfangtuijian
        ) {
            holder.dataBinding?.apply {
                root.setOnClickListener {
                    GameDetailActivity1.start(requireContext(),item.id)
                }
                data = item
                tvType.text = item.point +"   "+item.type + "   "+item.size
                kotlin.runCatching {
                    if(item.point.isNotEmpty()){
                        rb.rating = item.point.toFloat()
                    }
                }
            }
        }

    }

    //重磅推荐adapter
    private inner class  TuijianAdapter(beans:ArrayList<Game1>):BaseQuickAdapter<Game1,BaseDataBindingHolder<IncludeTuiBinding>>(R.layout.include_tui,beans){
        override fun convert(holder: BaseDataBindingHolder<IncludeTuiBinding>, item: Game1) {
            holder.dataBinding?.apply {
                data = item
                root.setOnClickListener {
                    GameDetailActivity1.start(requireContext(),item.id)
                }
                bku?.refreshView(
                    ShapeBlurView.build(context).setBlurMode(BlurMode.MODE_RECTANGLE)
//                        .setCornerRadius(BlurCorner.BOTTOM_RIGHT,  context.dip(13).toFloat())
//                        .setCornerRadius(BlurCorner.BOTTOM_LEFT, context.dip(13).toFloat())
                )
//                rev.layoutManager = LinearLayoutManager(requireContext(),RecyclerView.HORIZONTAL,false)
//                rev.adapter = BqSoildAdapter(R.layout.bq_item,item.biaoqian)
            }
        }

    }
    private inner class SortAdapter(layout:Int,beans:ArrayList<Fenlei>):BaseQuickAdapter<Fenlei,BaseViewHolder>(layout,beans){
        override fun convert(holder: BaseViewHolder, item: Fenlei) {
            holder.setText(R.id.tv1 ,item.name)
            holder.itemView.setOnClickListener {
                startActivity<OtherSortActivity>("type" to item.id,"name" to item.name)
            }
        }
    }
}